'use strict';

const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;

const db_name_user = 'star-community-user';
const db_user = db.collection(db_name_user);

exports.main = async (event, context) => {
  const flag = event.flag;

  if (flag === 0) { // id查询用户
    const {
      id,
    } = event.data;
    return await db_user.aggregate()
      .match({
        id,
      })
      .end();
  } else if (flag === 1) { // 添加用户
    const {
      id,
      unionid,
      openid_mp,
      openid_public,
      avatar,
      nickname,
      introduction,
      gender,
      backgroundImg,
      careCount,
      fansCount,
      likeCount,
      collectCount,
    } = event.data;
    return await db_user.add({
      id,
      isAdmin: false,
      unionid,
      openid_mp,
      openid_public,
      avatar,
      nickname,
      introduction,
      gender,
      backgroundImg,
      careCount,
      fansCount,
      likeCount,
      collectCount,
    });
  } else if (flag === 2) { // 更新用户
    const {
      id,
      updateData,
    } = event.data;
    return await db_user.where({
      id
    }).update({
      ...updateData,
    });
  } else if (flag === 3) { // openid_mp查询用户
    const {
      openid_mp,
    } = event.data;
    return await db_user.aggregate()
      .match({
        openid_mp,
      })
      .end();
  } else if (flag === 4) { // unionid查询用户
    const {
      unionid,
    } = event.data;
    return await db_user.aggregate()
      .match({
        unionid,
      })
      .end();
  }
};